const fs = require('fs');
const path = require('path');

exports.setPath = function(data, callback) {
	let oldPath = data.oldPath.replace(/\\/g, "/");
	let newPath = data.newPath.replace(/\\/g, "/");
	let fileName = data.fileName;
	let fileList = fileName.split(",");
	// 去空
	fileList = fileList.filter(function(s) {
		return s && s.trim();
	});
	const fileListHandle = fileList.map(item => {
		if(item.indexOf("sub") == -1){
			item = "sub" + item;
		}
		let itemOldPath = path.normalize(path.join(oldPath, item));
		let itemNewPath = path.normalize(path.join(newPath, item));
		return new Promise((resolve, reject) => {
			fs.open(itemOldPath, 'r+', function(err, fd) {
				if (err) {
					reject(item)
				} else {
					console.log('文件打开成功');
					resolve()
					fs.rename(itemOldPath, itemNewPath, (err) => {
						if (err) {
							console.log(err)
						} else {
							console.log('操作成功')
						}
					})
				}

			})
		}).catch(err => {
			return err
		})
	})
	return new Promise((resolve, reject) => {
		Promise.all(fileListHandle).then(res => {
			res = res.filter(function(s) {
				return s && s.trim();
			});
			console.log('操作失败的文件名:', res);
			resolve(res)
		}).catch(err => {
			console.log("err: ", err);
		});
	})

}
